package mul.Storage;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import com.swarmconnect.SwarmLeaderboardScore;
import com.swarmconnect.SwarmUser;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

/**
 *
 * Writes/reads an object to/from a private local file
 * 
 *
 */
public class LocalPersistence {

	private static final int MAX_LEADERBOARDENTERIES = 10;
	/**
	 * 
	 * @param context
	 * @param object
	 */
	public synchronized static void witeObjectToFile(Context context, Object object, String filename) {

		ObjectOutputStream objectOut = null;
		try {

			FileOutputStream fileOut = context.openFileOutput(filename, Activity.MODE_PRIVATE);
			objectOut = new ObjectOutputStream(fileOut);
			objectOut.writeObject(object);
			fileOut.getFD().sync();

			//            SwarmLeaderboardScore score = (SwarmLeaderboardScore) object;
			//            
			//            Log.i("help","WRITTEN TO LOCAL STORAGE   "+score.user.username+" =  "+score.score);


		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (objectOut != null) {
				try {
					objectOut.close();
				} catch (IOException e) {
					// do nowt
				}
			}
		}
	}


	/**
	 * 
	 * @param context
	 */
	public synchronized static Object readObjectFromFile(Context context, String filname)  {

		ObjectInputStream objectIn = null;
		Object object = null;


		try {

			FileInputStream fileIn = context.getApplicationContext().openFileInput(filname);
			objectIn = new ObjectInputStream(fileIn);
			object = objectIn.readObject();

			//            SwarmLeaderboardScore score = (SwarmLeaderboardScore) object;
			//            
			//            Log.i("help","READ FROM LOCAL STORAGE  "+score.user.username+" =  "+score.score);


		} catch (FileNotFoundException e) {
			// Do nothing
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (objectIn != null) {
				try {
					objectIn.close();
				} catch (IOException e) {
					// do nowt
				}
			}
		}


		return object;

	}


	public static SwarmLeaderboardScore[] buildLeaderBoardArray(List<SwarmLeaderboardScore> userScores){
		if(userScores != null){
			SwarmLeaderboardScore[] array = new SwarmLeaderboardScore[userScores.size()];

			for(int i=0;i< array.length; i++){
				array[i] = userScores.get(i);
				//Log.i("help",Float.toString(array[i].score ));
			}
			return array;
		}


		return null;
	}

	public static SwarmLeaderboardScore[] addScoreToArray(SwarmLeaderboardScore score, SwarmLeaderboardScore[] scores, int maxElements){

		Log.i("help", score.toString()+"  Added!");
		scores = sortArray(scores);
		Log.i("help", "LeaderBoardArray length  :"+scores.length);
		ArrayList<SwarmLeaderboardScore> myList = new ArrayList<SwarmLeaderboardScore>();

		for(int i=0;i<scores.length;i++){
			myList.add(scores[i]);

		}


		for(int i=0;i<myList.size();i++){
			SwarmLeaderboardScore currentScore = myList.get(i);
			if(currentScore.user.userId == score.user.userId){
				if(score.score >= currentScore.score){
					myList.set(i, score);
					break;
				}

			}else if(score.score >= myList.get(i).score){
				myList.add(i, score);
				break;
			}

		}



		scores = new SwarmLeaderboardScore[myList.size()];

		for(int i=0;i<scores.length;i++){
			scores[i] = myList.get(i);
			//Log.i("help","scores["+i+"]  =  "+scores[i]);
		}


		scores = sortArray(scores);

		if(scores.length>MAX_LEADERBOARDENTERIES){
			scores = trimArray(MAX_LEADERBOARDENTERIES, scores);
		}

		return scores;




	}
	public static SwarmLeaderboardScore[] sortArray(SwarmLeaderboardScore[] scores){


		if(scores.length > 1){

			SwarmLeaderboardScore score1;
			SwarmLeaderboardScore score2;

			for(int i=0; i<scores.length-2; i++){
				for(int j=i+1; j<scores.length-1; j++){
					score1 = scores[i];
					score2 = scores[j];
					//Log.i("help", "Iterartion: ["+i+", "+j+"]");

					if(score2.score > score1.score){
						scores[i] = score2;
						scores[j] = score1;
					}
				}
			}



		}else{

			if(scores.length==1 || scores.length ==0) return scores;



		}
		return scores;


	}


	public static SwarmLeaderboardScore[] trimArray(int size, SwarmLeaderboardScore[] array){
		SwarmLeaderboardScore[] temp = new SwarmLeaderboardScore[size];
		for(int i=0; i<size;i++){
			temp[i] = array[i];
			Log.i("help", temp[i].user.username);

		}

		return temp;




	}

}